var datatable;// 定义一个全局的dataTable
var d;
var exportColumns;//导出的列
var paras;//查询条件
$(function() {
//	getList();
	hideOrShow();
	showArearList("area");
	var jspType = $("#jspType").val();
	if(jspType.startWith(jspType,"kqi_evalution")){
		$("input[type='radio'][name=timeSize][value='"+$("#timeSize_link").val()+"']").attr("checked",true);
		if(jspType == 'kqi_evalution_zczdphTable'){
			$("input[type='radio'][name=radio][value='2']").attr("checked",true);
			$("#terminalBrandId").val($("#terminal_brand").val());
			loadTerminalModel();
		}else if(jspType == 'kqi_evalution_zcapnphTable'){
			$("input[type='radio'][name=radio][value='3']").attr("checked",true);
			$("#apnId").val($("#apn").val());
		}else if(jspType == 'kqi_evalution_zcxqTable'){
			$("input[type='radio'][name=radio][value='5']").attr("checked",true);
			$("#area").val($("#city_code").val());
		}else if(jspType == 'kqi_evalution_zcyhTable'){
			$("input[type='radio'][name=radio][value='1']").attr("checked",true);
			$("#userId").val($("#msisdn").val());
		}
		getRadio();
	}
	
	//新加的 SP Site
	var sp = $("#sp").val();
	 loadSite(sp);
	 $("#sp").combobox({
		select : function(event, ui) {
			loadSite();
		},
		width : 100
	 });
	
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});

	$("#groupId").combobox();
	$("#terminalBrandId").combobox({
		select:function(event,ui){
			loadTerminalModel();
		}
	});
	$("#terminalModelId").combobox();  
	$("#apnId").combobox();
	$("#sgw").combobox();

	$("input[name='timeSize']").change(function(){
		if($(this).val()=="hour"){
			$("#dnsServerBox").attr("disabled",true);
			$("#dnsServer").attr("disabled",true);
		}else{
			$("#dnsServerBox").attr("disabled",false);
			$("#dnsServer").attr("disabled",false);
		}
	})
	if($("#jspType").val() == 'kqiEvalution_dnscgl'){
		var timeSize_link = $("#timeSize_link").val();
		$("input[type='radio'][name=timeSize][value='"+timeSize_link+"']").attr("checked",true);
		if(timeSize_link=="hour"){
			$("#dnsServerBox").attr("disabled",true);
			$("#dnsServer").attr("disabled",true);
		}else{
			$("#dnsServerBox").attr("disabled",false);
			$("#dnsServer").attr("disabled",false);
		}
	}
	
})


//是否选择 域名  DNS服务器 展示的 查询维度
function hideOrShow(){
		var dominNameBoxChecked=  $("input[name='dominNameBox']").is(':checked');
		var dnsServerBoxChecked=  $("input[name='dnsServerBox']").is(':checked');
		if(dominNameBoxChecked == true || dnsServerBoxChecked ==true ){
			$("#selectedvalue_5").attr("disabled","disabled");
			$('#selectedvalue_0').attr("disabled","disabled"); 
			$('#selectedvalue_1').attr("disabled","disabled"); 
			$('#selectedvalue_2').attr("disabled","disabled"); 
			$('#selectedvalue_3').attr("disabled","disabled"); 
		}else {
			//$('#selectedvalue_5').removeAttr("disabled"); 
			//$('#selectedvalue_5').attr("disabled",""); 
			$("#selectedvalue_5").attr("disabled", false);
			$('#selectedvalue_0').attr("disabled",false); 
			$('#selectedvalue_1').attr("disabled",false); 
			$('#selectedvalue_2').attr("disabled",false); 
			$('#selectedvalue_3').attr("disabled",false); 
		}
}


/**
 * 新加   SP  site
 * 
 * 
 */

function loadSite(sp) {
	var sp = $("#sp").val();
	$.ajax({
				url : '../../feature/sp/getSiteInfos?sp='
					+ sp,
				type : 'POST',
				dataType : 'JSON',
				error : function() {
					alert('Error loading data!');
				},
				success : function(msg) {
					$("#site").remove();
					$("#site").empty();
					$("#siteTD")
							.append(
									$("<select id='site' name='site'></select>"));
					$("#site").combobox();
					$("#site").append("<option value=''>全部</option>");
					var list = msg.siteList;
					$.each(eval(list), function(i, item) {
						$(
								"<option value='" + item.site + "'>"
										+ item.site + "</option>")
								.appendTo($("#site"));
					});
				}
			});
  }

/**
 * 根据终端类型，加载终端型号
 * 
 * @param parentid
 */

function loadTerminalModel() {
	var terminalBrand = $("#terminalBrandId").val();

	$
			.ajax({
				url : '../../feature/terminalUE/terminalModelInfos?terminalBrand='
						+ terminalBrand,
				type : 'POST',
				dataType : 'JSON',
				error : function() {
					alert('Error loading data!');
				},
				success : function(msg) {
					$("#terminalModelId").remove();
					$("#terminalModelTD")
							.append(
									$("<select id='terminalModelId' name='terminalModelId'></select>"));
					
					$("#terminalModelId").append("<option value=''>全部</option>");
					var list = msg.terminalModelList;
					$.each(eval(list), function(i, item) {
						$(
								"<option value='" + item.terminal_model + "'>"
										+ item.terminal_model + "</option>")
								.appendTo($("#terminalModelId"));
					});
					
					if($("#jspType").val() == 'kqi_evalution_zczdphTable'){
						$("#terminalModelId").val($("#terminal_model").val());
					}
					$("#terminalModelId").combobox();
				}
				
				
			});

}

/**
 * 获得单选框
 */
function getRadio() {
	var selectedvalue = $("input[name='radio']:checked").val();
	for (var i = 0; i < 7; i++) {
		var tempId = '#radio_' + i;
		if (selectedvalue == i) {
			$(tempId).show();
		} else {
			$(tempId).hide();
		}
	}
}
/**
 * 页面校验
 */
function validatorParam(){
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	if(beginDate==null || beginDate==''){
		alert("请选择开始时间");
		return false;
	}
	if(endDate==null || endDate==''){
		alert("请选择结束时间");
		return false;
	}
	return true;
}

var col_index = 0;
function getList() {
	var timeSize = $('input:radio[name="timeSize"]:checked').val();
	console.log(timeSize)
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();

	// dnsName
	var dnsNameBox = $('input:checkbox[name="dnsNameBox"]:checked').val();
	var dnsName = $("#dnsName").val();

	//dnsServer
	var dnsServerBox=$('input:checkbox[name="dnsServerBox"]:checked').val();
	var dnsServer = $("#dnsServer").val();
	
	// 维度
	var selectRadio = $('input:radio[name="radio"]:checked').val();

	// SGW
	var sgw = $("#sgw").val();

	// 区域
	var cityCode = $("#area").val();
	var eNodeBID = "";
	var eNodeBIDCheck=false,areaHouseCheck=false;
	var areaHouse = "";

	if (selectRadio == '5') {// 区域
		//alert("enter if (selectRadio == '5')");
		// 处理areaBox多选框
		$("input[name='areaBox']:checkbox")
		.each(
				function() {
					if ($(this).attr("checked")) {
						var areatBoxId = $(this).val();
						//alert("areatBoxId=" + areatBoxId);
						if (areatBoxId == '1') {// eNodeBID
							eNodeBID = $("#eNodeBID").val();
							eNodeBIDCheck=true;
						} else if (areatBoxId == '2') {// 小区
							areaHouse = $("#areaHouse").val();
							areaHouseCheck=true;
						}
				}
		});
	}

	// 用户组
	var groupId = $("#groupId").val();

	// 用户
	var userId = $("#userId").val();

	// 终端类型
	var terminalBrandId = $("#terminalBrandId").val();
	var terminalModelId = $("#terminalModelId").val();
	// apn
	var apnId = $("#apnId").val();

	if(validatorParam()){
		//$("#table tbody tr").remove();
		$("#tbodyId").remove();
		$('#table').append($("<tbody id='tbodyId'></tbody>"));
		if (datatable == undefined || datatable == "undefined" || datatable == null) {
		} else {
			datatable.fnDestroy();
		}
		// 构造页面显示列
		var columns = createColumns(dnsServerBox,dnsNameBox, selectRadio,timeSize);
		var orderType = 'asc';
		if(dnsNameBox || dnsServerBox){
			orderType = 'desc';
		}else{
			col_index = 0;
			orderType = 'asc';
		}
		datatable = $('#table').dataTable({
			"order": [[ col_index, orderType ]],//默认排序
			"bPaginate" : true, // 翻页功能
			"bLengthChange" : false, // 改变每页显示数据数量
			"bFilter" : false, // 过滤功能
			"bSort" : true, // 排序功能
			"bInfo" : true,// 页脚信息
			"bAutoWidth" : true,// 自动宽度
			// "sPaginationType": "full_numbers",//显示分页的样式 还有simple_numbers等
			"iDisplayLength" : 50,
//			"sScrollX" : "100%",
			"sScrollXInner" : "110%",
			"bScrollCollapse" : true,
			"oLanguage" : {
				"sLengthMenu" : "每页显示 _MENU_条",
				"sZeroRecords" : "没有找到符合条件的数据",
				"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
				"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
				"sInfoEmpty" : "没有记录",
				"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
				"sSearch" : "搜索：",
				"oPaginate" : {
					"sFirst" : "首页",
					"sPrevious" : "前一页",
					"sNext" : "后一页",
					"sLast" : "尾页"
				}
			},
			"bProcessing" : true,
			"bServerSide" : true,
			"sAjaxSource" : "../../businessAnalysis/dns/getDns",
			"fnServerData" : function(sSource, aoData, fnCallback) {
				delete paras;
				paras = {
						"aoData" : JSON.stringify(aoData),
						"timeSize" : timeSize,
						"beginDate" : beginDate,
						"endDate" : endDate,
						"dnsNameBox": dnsNameBox,
						"dnsName" : dnsName,
						"selectRadio" : selectRadio,
						"groupId" : groupId,
						"userId" : userId,
						"terminalBrandId" : terminalBrandId,
						"terminalModelId" : terminalModelId,
						"apnId" : apnId,
						"sgw" : sgw,
						"cityCode" : cityCode,
						"eNodeBID" : eNodeBID,
						"eNodeBIDCheck" : eNodeBIDCheck,
						"areaHouse" : areaHouse,
						"areaHouseCheck" : areaHouseCheck,
						"dnsServerBox":dnsServerBox,
						"dnsServer":dnsServer
					};
				
				$.ajax({
					"type" : "post",
					"contentType" : "application/x-www-form-urlencoded",
					"url" : sSource,
					"dataType" : "json",
					"data" : paras, // 以json格式传递
					"success" : function(resp) {
						fnCallback(resp.pageDate);
						d = resp.allData;
					}
				});
			},
			columns : columns
			
		});
		
	}
}

/**
 * 构造页面显示的列
 * 
 * @param dnsNameBox
 * @param selectRadio
 */
function createColumns(dnsServerBox,dnsNameBox, selectRadio,timeSize) {
	//导出的列
	exportColumns = [];
	var columns = [];
	var trObj = $('#trId');
	trObj.children().remove();
	//时间
	trObj.append($("<th>时间</th>"));
	columns.push({
		data : "report_date"
	});
	exportColumns.push({
		"key":"report_date",
		"name":"时间",
		"value":""
	});
	col_index = 0;
	//根据页面条件显示
	// 显示域名
	if (dnsNameBox == '0') {
		trObj.append($("<th >域名</th>"));
		columns.push({
			data : "dns_name",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
		});
		exportColumns.push({
			"key":"dns_name",
			"name":"域名",
			"value":""
		});
		col_index++;
	}
	//显示dns服务器
	if(dnsServerBox == '0' && timeSize!='hour'){
		trObj.append($("<th >DNS服务器</th>"));
		columns.push({
			data : "destination_ip",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
		});
		exportColumns.push({
			"key":"destination_ip",
			"name":"DNS服务器",
			"value":""
		});
		col_index++;
	}
	
	// SWG
	if (selectRadio == '4') {
		trObj.append($("<th >SGW</th>"));
		columns.push({
			data : "sgw_name",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
		});
		
		exportColumns.push({
			"key":"sgw_name",
			"name":"SWG",
			"value":""
		});
		col_index++;
	} else if (selectRadio == '5') {// 区域
		// 城市
		trObj.append($("<th >地市</th>"));
		var cityName = "";
		if($("#citySel").val()){
			cityName = $("#citySel").val();
		}
		columns.push({
			data : "city_name"
//			render : function(value, type, row) {
//				return cityName;
//			}
		});
		exportColumns.push({
			"key":"city_code",
			"name":"地市",
			"value":cityName
		});
		col_index++;
		// 处理areaBox多选框
		$("input[name='areaBox']:checkbox")
				.each(
						function() {
							if ($(this).attr("checked")) {
								var areatBoxId = $(this).val();
								if (areatBoxId == '1') {// eNodeBID
									trObj.append($("<th >基站</th>"));
									columns.push({
										data : "enodebid"
									});
									exportColumns.push({
										"key":"enodebid",
										"name":"eNodeBID",
										"value":""
									});
									col_index++;
								} else if (areatBoxId == '2') {// 小区
									trObj.append($("<th >小区</th>"));
									columns.push({
										data : "cell_name"
									});
									exportColumns.push({
										"key":"cell_name",
										"name":"小区",
										"value":""
									});
									col_index++;
								}
							}
						});
	} else if (selectRadio == '0') {// 用户组
		trObj.append($("<th >用户组</th>"));
		//var groupName="";
		columns.push({
			data : "group_name"
//				,
//			render : function(value, type, row) {
//				$("#groupId option").each(function() {
//					if ($(this).val() == value) {
//						groupName = $(this).text();
//					}
//				});
//				return groupName;
//			}
		
		});
		exportColumns.push({
			"key":"group_name",
			"name":"用户组",
			"value" :""
		});
		col_index++;
	} else if (selectRadio == '1') {// 用户
		trObj.append($("<th >MSISDN</th>"));
		columns.push({
			data : "msisdn"
		});
		exportColumns.push({
			"key":"msisdn",
			"name":"MSISDN",
			"value":""
		});
		col_index++;
		trObj.append($("<th >IMSI</th>"));
		columns.push({
			data : "imsi"
		});
		exportColumns.push({
			"key":"imsi",
			"name":"IMSI",
			"value":""
		});
		col_index++;
	} else if (selectRadio == '2') {// 终端
		trObj.append($("<th >终端类型</th>"));
		var terminalBrandName="";
		columns.push({
			data : "terminal_brand",
			render : function(value, type, row) {
				$("#terminalBrandId option").each(function() {
					if ($(this).val() == value) {
						terminalBrandName = $(this).text();
					}
				});
				return terminalBrandName;
			}
		});
		exportColumns.push({
			"key":"terminal_brand",
			"name":"终端类型",
			"value":""
		});
		col_index++;
		var terminalModelName="";
		trObj.append($("<th >终端型号</th>"));
		columns.push({
			data : "terminal_model"
//			render : function(value, type, row) {
//				$("#terminalModelId option").each(function() {
//					if ($(this).val() == value) {
//						terminalModelName = $(this).text();
//					}
//				});
//				return terminalModelName;
//			}
		});
		exportColumns.push({
			"key":"terminal_model",
			"name":"终端型号",
			"value":""
		});
		col_index++;
	} else if (selectRadio == '3') {// apn
		trObj.append($("<th >APN</th>"));
		columns.push({
			data : "apn_name"
		});
		exportColumns.push({
			"key":"apn_name",
			"name":"APN",
			"value":""
		});
		col_index++;
	}
	
	//UDP请求次数
	trObj.append($("<th>UDP请求次数</th>"));
	columns.push({
		data : "udp_request_count"
	});
	exportColumns.push({
		"key":"udp_request_count",
		"name":"UDP请求次数",
		"value":""
	});
	col_index++;
	//UDP响应次数
	trObj.append($("<th>UDP响应次数</th>"));
	columns.push({
		data : "udp_resp_count"
	});
	exportColumns.push({
		"key":"udp_resp_count",
		"name":"UDP响应次数",
		"value":""
	});
	col_index++;
	//UDP响应成功率
	trObj.append($("<th>UDP响应成功率(%)</th>"));
	columns.push({
		data : "udp_resp_rate",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = "0";
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"udp_resp_rate",
		"name":"UDP响应成功率(%)",
		"value":""
	});
	col_index++;
	//UDP解析失败次数
	trObj.append($("<th>UDP解析失败次数</th>"));
	columns.push({
		data : "udp_failure_count"
	});
	exportColumns.push({
		"key":"udp_failure_count",
		"name":"UDP解析失败次数",
		"value":""
	});
	col_index++;
	//UDP响应时延
	trObj.append($("<th>UDP响应时延(ms)</th>"));
	columns.push({
		data : "udp_resp_time_delay"
	});
	exportColumns.push({
		"key":"udp_resp_time_delay",
		"name":"UDP响应时延",
		"value":""
	});
	//TCP请求次数
	trObj.append($("<th>TCP请求次数</th>"));
	columns.push({
		data : "tcp_request_count"
	});
	exportColumns.push({
		"key":"tcp_request_count",
		"name":"TCP请求次数",
		"value":""
	});
	//TCP响应次数
	trObj.append($("<th>TCP响应次数</th>"));
	columns.push({
		data : "tcp_resp_count"
	});
	exportColumns.push({
		"key":"tcp_resp_count",
		"name":"TCP响应次数",
		"value":""
	});
	//TCP响应次数
	trObj.append($("<th>TCP响应成功率(%)</th>"));
	columns.push({
		data : "tcp_resp_rate",
		render : function(value, type, row) {
			if (value == null || value == "") {
				value = "0";
			}
			return value;
		}
	});
	exportColumns.push({
		"key":"tcp_resp_rate",
		"name":"TCP响应成功率(%)",
		"value":""
	});
	//TCP解析失败次数
	trObj.append($("<th>TCP解析失败次数</th>"));
	columns.push({
		data : "tcp_failure_count"
	});
	exportColumns.push({
		"key":"tcp_failure_count",
		"name":"TCP解析失败次数",
		"value":""
	});
	//TCP响应时延
	trObj.append($("<th>TCP响应时延(ms)</th>"));
	columns.push({
		data : "tcp_resp_time_delay"
	});
	exportColumns.push({
		"key":"tcp_resp_time_delay",
		"name":"TCP响应时延",
		"value":""
	});
	return columns;
}

function resetQueryForm() {
	$('#queryForm')[0].reset();
	getRadio();
}

function exportExcel() {
	if (d) {
		paras['exportColumns'] = JSON.stringify(exportColumns);
		$.ajax({
			type : "POST",
			url : "../../businessAnalysis/dns/exportBigDataExcel?rand="
					+ Math.random(),
			dataType : "json",
			"data" : paras,
			success : function(data) {
				if (data.flag) {
					var url = "../../businessAnalysis/dns/downFiles?path="
							+ data.path;
					window.location.href = url;
				} else {
					alert(data.msgs);
				}
			}
		});
	} else {
		alert("请先查询数据！");
	}
}

// 下拉树 begin
function onClick(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree
			.getSelectedNodes(), v = "";
	nodes.sort(function compare(a, b) {
		return a.id - b.id;
	});
	for (var i = 0, l = nodes.length; i < l; i++) {
		v += nodes[i].name + ",";
	}
	if (v.length > 0)
		v = v.substring(0, v.length - 1);
	var cityObj = $("#citySel");
	cityObj.attr("value", v);
	$("#area").val(treeNode.id);

	hideMenu();
}
/**
 * 显示树
 */
function showMenu() {
	var cityObj = $("#citySel");
	var cityOffset = $("#citySel").offset();
	$("#menuContent").css({
		left : cityOffset.left - 26 + "px",
		top : cityOffset.top - 206 + "px"
	}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}
/**
 * 隐藏树
 */
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(
			event.target).parents("#menuContent").length > 0)) {
		hideMenu();
	}
}

String.prototype.startWith = function(s) {
	if (s == null || s == "" || this.length == 0 || s.length > this.length)
		return false;
	if (this.substr(0, s.length) == s)
		return true;
	else
		return false;
	return true;
}